<?php

namespace App\Logics;


use App\Models\Student;
use App\Models\User;
use App\Service\Base\Logic;

class StudentLogic extends Logic
{

    // 学员：认证学校添加学员
    //   只针对当前的学校认证用户才有的操作

    // 添加学员
    // 修改学员
    // 删除学员
    // 学员列表
    public function onLists()
    {
        $opt    = $this->option();
        $page   = $opt->getData('page', 0, 'intval');
        $rows   = $opt->getData('rows', 15, 'intval');
        $start  = $page ? ($page - 1) * $rows : 0;
        $isPage = $opt->getData('is_count', 0, 'intval');  // 是否需要翻页

        // 模型 和 查询
        $lRes  = $this->listWhere();
        $where = $lRes[0];
        $bang  = $lRes[1];


        // 执行
        $model = new Student();

        /*$KCache = $model->cacheKey('lists', $where);
        $lists  = $model->cacheClass()->getCache($KCache);
        if(empty($lists)){}*/
        // ->bangField($bang)
        if($isPage){
            $result = $model->listPage($where, $page, $rows, "id DESC");
        } else{
            $result = $model->getList($where, $rows, "id DESC", $start);
        }

        return $result;
    }


    // 统计：主要用户pc端
    public function onCount()
    {
        $lRes  = $this->listWhere();
        $where = $lRes[0];

        // 执行
        $rows   = $this->option()->getData('rows', 15, 'intval');
        $model  = new Student();
        $nums   = $model->where($where)->count();
        $pages  = ceil($nums / $rows);
        $result = ['total' => $nums, 'pages' => $pages,];

        return $result;
    }


    // 学员详情
    public function onShow()
    {
        $student_id = $this->option()->getData('student_id', 0, 'intval');
        if(empty($student_id)){
            return $this->_returnFail('请指定要查看的记录！');
        }

        $model = new Student();
        $info  = $model->isCache(true)->oneFind(['id' => $student_id]);
        $user  = (new User())->isCache(true)->oneFind(['id' => $info['uid']]);
        // 组合
        $info['user'] = $user;

        return $info;
    }

    // 直接删除
    public function onDelete($myUid)
    {
        $opt  = $this->option();
        $_ids = $opt->getData('ids', [], 'is_array');
        $_id  = $opt->getData('id', 0, 'intval');
        if(empty($_id)){
            return $this->_returnFail('请指定删除记录');
        }

        $where  = ['id' => $_id, 'uid' => $myUid];
        $model  = new Student();
        $result = $model->isCache(true)->oneDelete($where);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 直接删除
    public function batchDelete($myUid)
    {
        $opt  = $this->option();
        $_ids = $opt->getData('ids', [], 'is_array');
        if(empty($_ids)){
            return $this->_returnFail('请指定删除记录');
        }

        $where = ['uid' => $myUid];
        $model = new Student();
        $list  = $model->whereIn('id', $_ids)->where($where)->get();  //->recycle()
        if($list->isEmpty()){
            return $this->_returnFail('你要删除的数据不存在！！');
        }

        // 缓存操作
        $model->deleteCacheList($list);
        $res = $model->whereIn('id', $_ids)->where($where)->delete();  //->recycle()

        return $res;
    }

    // 删除
    public function allDelete($ids)
    {
        $list = $this->whereIn('id', $ids)->first();  //->recycle()
        if(empty($list)){
            return $this->return_false('你要删除的数据不存在！！');
        }

        // 缓存操作
        $this->deleteCacheList($list);

        return $list->delete();
    }

    // 软删除
    public function onSoft($myUid)
    {
        $opt = $this->option();
        $_id = $opt->getData('id', 0, 'intval');
        if(empty($_id)){
            return $this->_returnFail('请指定删除记录');
        }

        $where  = ['id' => $_id, 'uid' => $myUid];
        $model  = new Student();
        $result = $model->isCache(true)->oneEdit($where, ['status' => -1]);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }


    // 改变（直接修改，软删除，改变状态，排序）
    public function onEdit($myUid)
    {
        $opt = $this->option();
        $_id = $opt->getData('id', 0, 'intval');
        if(empty($_id)){
            return $this->_returnFail('请指定修改的ID编号！');
        }


        // 获取认证编号
        $user = (new User())->isCache(true)->oneFind(['id' => $myUid]);
        if(empty($user)){
            return $this->_returnFail('用户不存在！');
        }
        if(empty($user['is_auth'])){
            return $this->_returnFail('你没有认证！');
        }
        if($user['verify'] != 1){
            return $this->_returnFail('你的用户认证未通过！');
        }

        $auth_id = $user['auth_id'];
        $mobile  = $opt->getData("mobile", null, "trim");
        $data    = [
            //'id'          => $opt->getData("id", null, "intval"),
            //'uid'         => $myUid,
            //'auth_id'     => $auth_id,
            'person_uid'  => $opt->getData("person_uid", null, "intval"),
            'person_name' => $opt->getData("person_name", null, "trim"),
            'head_img'    => $opt->getData("head_img", null, "trim"),
            'sex'         => $opt->getData("sex", null, "intval"),
            'age'         => $opt->getData("age", null, "intval"),
            'mobile'      => $mobile,
            'guardor'     => $opt->getData("guardor", null, "trim"),
            'is_remind'   => $opt->getData("is_remind", null, "intval"),
            'status'      => $opt->getData("status", 0, "intval"),
            //'ctime'       => $opt->getData("ctime", null, "intval"),
            //'mtime'       => $opt->getData("mtime", null, "intval"),
        ];

        // 头像
        $data['head_img'] = $this->randHeadImg($data['head_img']);
        if(!preg_match('/^1[3-9]\d{9}$/', $data['mobile'])){
            return $this->_returnFail('请输入正确手机号！');
        }

        // 过滤空
        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 判断学员是否已经存在
        $model   = new Student();
        $hWhere  = [['uid', '=', $myUid], ['mobile', '=', $mobile], ['id', '<>', $_id],];
        $hasInfo = $model->isCache(true)->oneFind($hWhere);
        if($hasInfo){
            return $this->_returnFail('你已经添加该学员！');
        }

        // 获取用户信息  更新学员状态
        $userWhere = ['mobile' => $data['mobile'], 'status' => 1];
        $userInfo  = (new User())->isCache(true)->oneFind($userWhere);
        if($userInfo){
            $userInfo = is_object($userInfo) ? $userInfo->toArray() : $userInfo;
            // 学员状态
            $data['person_uid'] = $userInfo['id'];
            $data['status']     = 1;
        }

        // 组合数据
        $where = ['id' => $_id, 'uid' => $myUid];
        $data  = $model->checkData($data, $where);
        if($data === false){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 验证
        $result = $model->checkRules($data, 'edit');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 树状
    public function onAdd($myUid)
    {
        $opt = $this->option();
        // 获取认证编号
        $user = (new User())->isCache(true)->oneFind(['id' => $myUid]);
        if(empty($user)){
            return $this->_returnFail('用户不存在！');
        }
        if(empty($user['is_auth'])){
            return $this->_returnFail('你没有认证！');
        }
        if($user['verify'] != 1){
            return $this->_returnFail('你的用户认证未通过！');
        }

        $auth_id = $user['auth_id'];
        $mobile  = $opt->getData("mobile", null, "trim");
        $data    = [
            //'id'          => $opt->getData("id", null, "intval"),
            'uid'         => $myUid,
            'auth_id'     => $auth_id,
            'person_uid'  => $opt->getData("person_uid", null, "intval"),
            'person_name' => $opt->getData("person_name", null, "trim"),
            'head_img'    => $opt->getData("head_img", null, "trim"),
            'sex'         => $opt->getData("sex", null, "intval"),
            'age'         => $opt->getData("age", null, "intval"),
            'mobile'      => $mobile,
            'guardor'     => $opt->getData("guardor", null, "trim"),
            'is_remind'   => $opt->getData("is_remind", null, "intval"),
            'status'      => $opt->getData("status", 0, "intval"),
            //'ctime'       => $opt->getData("ctime", null, "intval"),
            //'mtime'       => $opt->getData("mtime", null, "intval"),
        ];

        // 头像
        $data['head_img'] = $this->randHeadImg($data['head_img']);
        if(!preg_match('/^1[3-9]\d{9}$/', $data['mobile'])){
            return $this->_returnFail('请输入正确手机号！');
        }

        // 判断是否已经添加该学员
        $model   = new Student();
        $hWhere  = [['uid', '=', $myUid], ['mobile', '=', $mobile],];
        $hasInfo = $model->isCache(true)->oneFind($hWhere);
        if($hasInfo){
            return $this->_returnFail('你已经添加该学员！');
        }

        // 获取用户信息  更新学员状态
        $userWhere = ['mobile' => $data['mobile'], 'status' => 1];
        $userInfo  = (new User())->isCache(true)->oneFind($userWhere);
        if($userInfo){
            $userInfo = is_object($userInfo) ? $userInfo->toArray() : $userInfo;
            // 学员状态
            $data['person_uid'] = $userInfo['id'];
            $data['status']     = 1;
        }

        // 过滤空
        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 组合数据
        $data = $model->checkData($data);
        if($data === false){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 验证
        $result = $model->checkRules($data, 'add');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        $result = $model->oneAdd($data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 列表查询
    protected function listWhere()
    {
        $option  = $this->option();
        $where   = [];
        $bang    = [];
        $c_id    = $option->getData('course_id', 0, 'intval');
        $myUid   = $option->getData('myUid', 0, 'intval');
        $age     = $option->getData('age', 0, 'intval');
        $sex     = $option->getData('sex', null, 'intval');
        $status  = $option->getData('status', 0, 'trim');
        $mobile  = $option->getData('mobile', null, 'trim');
        $name    = $option->getData('name', null, 'trim');
        $p_name  = $option->getData('person_name', null, 'trim');
        $keyword = $option->getData('keyword', null, 'trim');
        if($c_id){
            $bang[]  = 'course_id';
            $where[] = ['course_id', '=', $c_id];
        }
        if($myUid){
            $bang[]  = 'uid';
            $where[] = ['uid', '=', $myUid];
        }
        if($age){
            $bang[]  = 'age';
            $where[] = ['age', '=', $age];
        }
        if(!is_null($sex)){
            $bang[]  = 'sex';
            $where[] = ['sex', '=', $sex];
        }
        if(!is_null($status)){
            // 没有删除
            if($status == 999){
                $bang[]  = 'status';
                $where[] = ['status', '>=', 0];
            } else{
                $bang[]  = 'status';
                $where[] = ['status', '=', $status];
            }
        }
        if($mobile){
            $bang    = false;
            $where[] = ['mobile', 'like', "%".$mobile."%"];
        }
        if($name){
            $bang    = false;
            $where[] = ['person_name', 'like', "%".$name."%"];
        }
        if($p_name){
            $bang    = false;
            $where[] = ['person_name', 'like', "%".$p_name."%"];
        }
        if($keyword){
            $bang = false;
            //$where[] = $this->orWhere('username|nickname|mobile', 'like', $keyword);
        }

        return [$where, $bang];
    }

    // 随机用户头像
    protected function randHeadImg($url = '')
    {
        if($url){
            return $url;
        }

        // 从数组中随机获取
        // $imgs = [];
        // $_key = array_rand($imgs);
        // $img  = $imgs[$_key];

        // 从七牛云中获取
        // 纯色头像：已经删除 'https://img.shenlanhui.com/static/sys_head_img/face_'.rand(1, 75).'.jpg';
        // 一般头像 'https://img.shenlanhui.com/static/head_img/face_'.rand(1, 450).'.jpg';
        $img = 'https://img.shenlanhui.com/static/head_img/face_'.rand(1, 450).'.jpg';

        return $img;
    }

}


